<template>
  <div class="callCenterInfos">
    <TitleName
      class="title mb-20px"
      icon="i-carbon-bookmark-filled"
      title="基础信息"
    ></TitleName>
    <div
      v-if="isEdit ? isEdit : !isDetail"
      class="mb-20px autocompleteStye"
      style="display: flex; justify-content: space-between"
    >
      <div>
        <el-autocomplete
          v-model="customerNameOrNumber"
          :fetch-suggestions="customerNameFetch"
          :popper-class="'callCenterInfos-form-select'"
          clearable
          placeholder="请输入客户名称/税号"
          style="width: 350px; margin-right: 15px"
          @select="customerNameSelect"
        >
          <template v-if="isSearchDataNo" v-slot="{ item }">
            <div class="default">{{ item.default }}</div>
          </template>
        </el-autocomplete>
        <el-button type="primary" @click="handleBtn('jump')"
          >新增客户</el-button
        >
      </div>
      <div>
        <div
          v-if="!route.query.TAX_CODE && phoneRecordInfos.isNuoYan != '1'"
          class="callCenterInfos-form-select styFormRadio"
          style="
            display: inline-block;
            margin-right: 20px;
            vertical-align: bottom;
          "
        >
          <el-radio-group
            v-model="formData.type"
            :disabled="isEdit ? false : isDetail"
          >
            <el-radio
              v-for="(dict, index) in biz_call_record_type"
              :key="index"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </div>
        <el-button
          v-if="!route.query.TAX_CODE"
          :disabled="successdialog"
          :loading="abnormaSaveBtnLoading"
          plain
          type="info"
          @click="handleBtn('abnormal')"
          >保存异常单据</el-button
        >
        <el-button type="primary" @click="handleBtn('copy')">复制</el-button>
        <el-button
          v-if="!route.query.abId"
          :disabled="successdialog"
          :loading="saveBtnLoading"
          type="primary"
          @click="saveFn"
          >保存</el-button
        >
      </div>
    </div>
    <!-- 基本信息 -->
    <el-form
      ref="ruleForm"
      :model="formData"
      :rules="
        !route.query.abId && route.path.indexOf('phoneRecordSheet') != -1
          ? formRules
          : {}
      "
      class="callCenterInfos-form mb-20px"
      label-position="right"
      label-width="150px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-input
              v-model="formData.customerName"
              maxlength="50"
              placeholder=""
              readonly
              @focus="focusTip"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="企业税号" prop="customerTaxcode">
            <el-input
              v-model="formData.customerTaxcode"
              maxlength="50"
              placeholder=""
              readonly
              @focus="focusTip"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户类别" prop="customerType">
            <el-select
              v-model="formData.customerType"
              :popper-class="'callCenterInfos-form-select'"
              clearable
              disabled
              placeholder="请选择客户类别"
              style="width: 100%"
            >
              <el-option
                v-for="(dict, index) in customer_class"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属税务机关" prop="taxdeptCode">
            <el-tree-select
              v-model="formData.taxdeptCode"
              :check-strictly="true"
              :data="taxTreeData"
              :props="{
                value: 'id',
                label: 'label',
                children: 'children'
              }"
              disabled
              filterable
              node-key="id"
              placeholder="填写所属税务机关"
              style="width: 100%"
              value-key="id"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户等级" prop="customerLevel">
            <el-select
              v-model="formData.customerLevel"
              disabled
              placeholder="请选择客户等级"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in customer_level"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="盘是否注销" prop="isCancel">
            <el-radio-group
              v-model="formData.isCancel"
              :disabled="isEdit ? false : isDetail"
            >
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="stySelect">
          <el-form-item label="数电配置" prop="isDigital">
            <el-radio-group
              v-model="formData.isDigital"
              :disabled="isEdit ? false : isDetail"
            >
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
            <el-select
              v-if="formData.isDigital == 1"
              v-model="formData.digitalInfo"
              :disabled="isEdit ? false : isDetail"
              :popper-class="'callCenterInfos-form-select'"
              class="w-full"
              placeholder="请选择数电信息"
              style="width: 50%; margin-left: 20px"
            >
              <el-option
                v-for="(item, index) in biz_digital_info"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会员等级" prop="memberLevel">
            <el-input
              v-model="formData.memberLevel"
              disabled
              maxlength="50"
              style="width: 50%"
            ></el-input>
            <el-button
              plain
              size="small"
              style="cursor: pointer; font-size: 15px; height: 30px"
              type="success"
              @click="qualifications"
              >诺诺资质</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="固定电话" prop="telephone">
            <el-input
              v-model="formData.telephone"
              :disabled="isEdit ? false : isDetail"
              clearable
              maxlength="20"
              placeholder="请输入固定电话"
            ></el-input>
          </el-form-item>
        </el-col>

        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="客户星级" prop="starRating">-->
        <!--            <el-rate-->
        <!--              v-model="formData.starRating"-->
        <!--              :disabled="isEdit ? false : isDetail"-->
        <!--              allow-half-->
        <!--              class="pl-10px"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="12">
          <el-form-item label="纳税人性质" prop="taxNature">
            <el-select
              v-model="formData.taxNature"
              :disabled="isEdit ? false : isDetail"
              :popper-class="'callCenterInfos-form-select'"
              class="w-full"
              clearable
              placeholder="纳税人性质"
              style="width: 100%"
              @change="taxNatureFn"
            >
              <el-option
                v-for="(dict, index) in tax_grade"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
            <!--            <el-button class="ml-20px" type="primary" @click="checkInfo"-->
            <!--              >获取最新</el-button-->
            <!--            >-->
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="客户备注" prop="customerRemark">
            <el-input
              v-model="formData.customerRemark"
              :disabled="isEdit ? false : isDetail"
              clearable
              maxlength="100"
              placeholder="请输入客户备注"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="mainContactName">
            <el-input
              v-model="formData.mainContactName"
              :disabled="isEdit ? false : isDetail"
              clearable
              maxlength="15"
              placeholder="请输入联系人"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="mainContactPhone">
            <el-input
              v-model="formData.mainContactPhone"
              :disabled="isEdit ? false : isDetail"
              clearable
              maxlength="20"
              placeholder="请输入联系电话"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" style="border-bottom: 0.5px solid #ebeef5">
          <el-form-item label="联系地址" prop="address">
            <el-input
              v-model="formData.address"
              :disabled="isEdit ? false : isDetail"
              clearable
              maxlength="50"
              placeholder="请输入联系地址"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <TitleName
        class="title mb-20px mt-20px"
        icon="i-carbon-bookmark-filled"
        title="问题录入"
      ></TitleName>
      <el-row class="mt-20px">
        <el-col :span="24">
          <el-form-item label="问题分类" prop="questionTypeName">
            <el-cascader
              ref="questionType"
              v-model="questionTypeIdSelect"
              :disabled="isEdit ? false : isDetail"
              :filter-method="filterMethodFn"
              :options="questionTypeOptions"
              :popper-class="'callCenterInfos-form-select'"
              :props="questionTypeProps"
              clearable
              filterable
              placeholder="请选择问题分类"
              style="width: 100%"
              @change="questionTypePropsChange"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="产品名称" prop="productId">-->
        <!--            <el-select-->
        <!--              v-model="formData.productId"-->
        <!--              :disabled="isEdit ? false : isDetail"-->
        <!--              :filter-method="productIdfilterMethod"-->
        <!--              :popper-class="'callCenterInfos-form-select'"-->
        <!--              clearable-->
        <!--              filterable-->
        <!--              placeholder="请输入关键词"-->
        <!--              style="width: 100%"-->
        <!--              @change="productChange"-->
        <!--            >-->
        <!--              <el-option-->
        <!--                v-for="item in filteredOptions"-->
        <!--                :key="item.productId"-->
        <!--                :label="item.productName"-->
        <!--                :value="item.productId"-->
        <!--              >-->
        <!--              </el-option>-->
        <!--            </el-select>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="12" class="styTextarea">
          <el-form-item label="问题描述" prop="questionContent">
            <el-input
              v-model="formData.questionContent"
              :disabled="isEdit ? false : isDetail"
              autosize
              clearable
              maxlength="100"
              placeholder="请输入问题描述"
              type="textarea"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="styTextarea">
          <el-form-item label="问题答案" prop="questionAnswer">
            <el-input
              v-model="formData.questionAnswer"
              :disabled="isEdit ? false : isDetail"
              autosize
              clearable
              maxlength="100"
              placeholder="请输入问题答案"
              type="textarea"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col v-if="formData.isNuoYan == 1" :span="24">
          <el-form-item label="处理方式" prop="processMode">
            <el-select
              v-model="formData.processMode"
              clearable
              placeholder="请选择处理方式"
              style="width: 70%"
            >
              <el-option
                v-for="(dict, index) in biz_process_mode"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="formData.isNuoYan == 1" :span="12">
          <el-form-item label="开始时间" prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              :popper-class="'callCenterInfos-form-select'"
              clearable
              placeholder="请选择开始时间"
              style="width: 100%"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="formData.isNuoYan == 1" :span="12">
          <el-form-item label="结束时间" prop="finishDate">
            <el-date-picker
              v-model="formData.finishDate"
              :popper-class="'callCenterInfos-form-select'"
              clearable
              placeholder="请选择结束时间"
              style="width: 100%"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="formData.isDispatch == 1 ? 12 : 24">
          <el-form-item label="是否需要派单" prop="isDispatch">
            <el-radio-group
              v-model="formData.isDispatch"
              :disabled="isEdit ? false : isDetail"
            >
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="formData.isDispatch == 1" :span="12">
          <el-form-item label="地址说明" prop="selectAddress">
            <el-select
              v-model="formData.selectAddress"
              :popper-class="'callCenterInfos-form-select'"
              clearable
              placeholder="请选择地址说明"
              style="width: 100%"
              @change="selectAddressChange"
            >
              <el-option
                v-for="(dict, index) in selectAddressArr"
                :key="index"
                :label="dict.addressName"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="formData.isDispatch == 1">
        <el-col :span="12" class="stySelect">
          <el-form-item label="预约时间" prop="reservationDate">
            <el-date-picker
              v-model="formData.reservationDate"
              :disabled="isEdit ? false : isDetail"
              :popper-class="'callCenterInfos-form-select'"
              clearable
              placeholder="请选择预约时间"
              style="width: 50%"
              type="date"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
            <el-select
              v-model="formData.reservationPeriod"
              :disabled="isEdit ? false : isDetail"
              :popper-class="'callCenterInfos-form-select'"
              class="w-full"
              clearable
              placeholder="请选择时间段"
              style="width: 40%"
            >
              <el-option
                v-for="(dict, index) in biz_reservation_period"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="派单联系人" prop="dispatchContact">
            <el-input
              v-model="formData.dispatchContact"
              :disabled="isEdit ? false : isDetail"
              clearable
              maxlength="20"
              placeholder="请输入派单联系人"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="派工类型" prop="sendTypeId">
            <el-select
              v-model="formData.sendTypeId"
              :disabled="isEdit ? false : isDetail"
              :popper-class="'callCenterInfos-form-select'"
              class="w-full"
              placeholder="请选择派工类型"
              style="width: 100%"
            >
              <el-option
                v-for="(dict, index) in biz_call_record_send_type"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="派单联系电话" prop="dispatchPhone">
            <el-input
              v-model="formData.dispatchPhone"
              :disabled="isEdit ? false : isDetail"
              clearable
              maxlength="20"
              placeholder="请输入派单联系电话"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="派单地址" prop="dispatchAddress">
            <el-input
              v-model="formData.dispatchAddress"
              :disabled="isEdit ? false : isDetail"
              clearable
              maxlength="50"
              placeholder="请输入派单地址"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <TitleName
      class="title mb-20px"
      icon="i-carbon-bookmark-filled"
      title="来电记录"
    ></TitleName>
    <el-table :data="tableList" border>
      <el-table-column label="来电时间" prop="telDate" width="180">
      </el-table-column>
      <!--      <el-table-column label="来电人" prop="telPerson" width="110" />-->
      <el-table-column label="来电电话" prop="personTel" width="130" />
      <el-table-column label="是否已派单" prop="dispatchMark" width="130" />
      <el-table-column label="受理人" prop="userName" width="110" />
      <el-table-column label="问题分类" prop="questionTypeName" />
      <el-table-column label="问题描述" prop="questionContent" questionAnswer />
      <el-table-column label="问题答案" prop="questionAnswer" />
    </el-table>
    <!--      提交成功-->
    <el-dialog
      v-model="successdialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      center
      title="温馨提示"
      width="250"
    >
      <div class="text-20px mb-10px text-center">保存成功！</div>
      <div class="w-100% text-right">
        <el-button type="primary" @click="successdialogClose"
          >{{ successdialogSencond }}秒后关闭</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script name="PRSinformation" setup>
import { getCurrentInstance, nextTick } from 'vue'
import { find } from 'lodash'
import { useRouter, useRoute } from 'vue-router'
import useClipboard from 'vue-clipboard3'
import {
  getDetailTactlist,
  getListByCustomer
} from '@/api/customerManage/customerList'
const { toClipboard } = useClipboard()
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
import useUserStore from '@/store/modules/user'
import useCommonStore from '@/store/modules/common'
import {
  callRecordDetail,
  callRecordSave,
  callRecordUpdate,
  getLevel,
  productList,
  questionTyplist,
  recordList,
  listByCustomerFromView,
  abnormalSave,
  abnormalDeatils
} from '@/api/callCenter'
const userStore = useUserStore()
const commonStore = useCommonStore()
import { format } from 'date-fns'
const {
  customer_class,
  customer_level,
  tax_grade,
  biz_digital_info,
  biz_reservation_period,
  biz_call_record_type,
  biz_call_record_send_type,
  biz_process_mode
} = proxy.useDict(
  'customer_class',
  'customer_level',
  'tax_grade',
  'biz_digital_info',
  'biz_reservation_period',
  'biz_call_record_type',
  'biz_call_record_send_type',
  'biz_process_mode'
)
// 接受父级传递的参数
const props = defineProps({
  //来电电话
  telCalls: {
    required: true,
    type: String,
    default: () => {
      return ''
    }
  },
  paramData: {
    required: true,
    type: Object || Array,
    default: () => {
      return {}
    }
  }
})
const formDataVal = {
  customerName: '',
  customerTaxcode: '',
  customerType: '',
  taxdeptCode: '',
  customerLevel: '',
  isCancel: '0',
  isDigital: '0',
  sendTypeId: '1', //派工类型--维护
  type: '1', //来电类型
  digitalInfo: '',
  customerRemark: '',
  telephone: '',
  memberLevel: '',
  starRating: 0,
  taxNature: '',
  address: '',
  mainContactName: '',
  mainContactPhone: '',
  questionTypeName: '',
  questionTypeId: '', //问题分类
  questionContent: '',
  questionAnswer: '', //问题答案
  isDispatch: '0', //是否需要派单
  reservationDate: '',
  reservationPeriod: '全天', //预约时间段
  dispatchAddress: '', //派单地址
  dispatchContact: '', //派单联系人
  dispatchPhone: '', //派单联系电话
  productId: '2504',
  productName: '其 它',
  startDate: format(new Date(), 'yyyy-MM-dd HH:mm:ss'),
  finishDate: '',
  processMode: '2',
  isNuoYan: '0',
  selectAddress: undefined,
  addrName: undefined
}
const data = reactive({
  customerNameOrNumber: '', //输入客户名称/税号
  isSearchDataNo: false, //是否搜索的数组为[]
  formData: formDataVal, //表单数据
  formRules: {
    customerName: [
      {
        required: true,
        message: '客户名称不能为空',
        trigger: ['blur', 'change']
      }
    ],
    customerTaxcode: [
      {
        required: true,
        message: '企业税号不能为空',
        trigger: ['blur', 'change']
      }
    ],
    // customerType: [
    //   { required: true, message: '请选择客户类别', trigger: ['blur', 'change'] }
    // ],
    // taxdeptCode: [
    //   {
    //     required: true,
    //     message: '请选择所属税务机关',
    //     trigger: ['blur', 'change']
    //   }
    // ],
    // customerLevel: [
    //   {
    //     required: true,
    //     message: '请选择客户等级',
    //     trigger: ['blur', 'change']
    //   }
    // ],
    // starRating: [
    //   {
    //     required: true,
    //     message: '请选择客户星级',
    //     trigger: ['blur', 'change']
    //   }
    // ],
    taxNature: [
      {
        required: true,
        message: '请选择纳税人性质',
        trigger: ['blur', 'change']
      }
    ],
    mainContactPhone: [
      {
        required: true,
        message: '请输入联系电话',
        trigger: ['blur', 'change']
      }
    ],
    mainContactName: [
      {
        required: true,
        message: '请输入联系人',
        trigger: ['blur', 'change']
      }
    ],
    address: [
      {
        required: true,
        message: '请输入联系地址',
        trigger: ['blur', 'change']
      }
    ],
    questionAnswer: [
      {
        required: true,
        message: '请选择问题答案',
        trigger: ['blur', 'change']
      }
    ],
    questionTypeName: [
      {
        required: true,
        message: '请选择问题分类',
        trigger: ['blur', 'change']
      }
    ],
    questionContent: [
      {
        required: true,
        message: '请选择问题描述',
        trigger: ['blur', 'change']
      }
    ],
    // productId: [
    //   {
    //     required: true,
    //     message: '请输入产品名称',
    //     trigger: ['blur', 'change']
    //   }
    // ],
    dispatchContact: [
      {
        required: true,
        message: '请输入派单联系人',
        trigger: ['blur', 'change']
      }
    ],
    dispatchPhone: [
      {
        required: true,
        message: '请输入派单联系电话',
        trigger: ['blur', 'change']
      }
    ],
    dispatchAddress: [
      {
        required: true,
        message: '请输入派单地址',
        trigger: ['blur', 'change']
      }
    ],
    selectAddress: [
      {
        required: true,
        message: '请选择地址说明',
        trigger: ['blur', 'change']
      }
    ]
  }
})
const { customerNameOrNumber, formData, formRules, isSearchDataNo } =
  toRefs(data)
/*************按钮的操作  *********************/
const abnormaSaveBtnLoading = ref(false)
const handleBtn = async type => {
  switch (type) {
    case 'jump':
      //新增客户
      window.open(
        '/customerManage/customerModules/customerAdd?flag=add',
        'scrollbars=yes,resizable=1,modal=false,alwaysRaised=yes'
      )
      break
    case 'copy':
      //复制
      if (!formData.value.customerName) {
        proxy.$message.error('客户名称不能为空')
        return false
      }
      let prarm = {
        orgName: phoneRecordInfos.value.orgName || '',
        customerName: formData.value.customerName || '',
        customerTaxcode: formData.value.customerTaxcode || '',
        telCalls: props.telCalls || '',
        promptMessage: phoneRecordInfos.value.promptMessage || '',
        expirationDate: phoneRecordInfos.value.expirationDate || '',
        questionContent: formData.value.questionContent || ''
      }
      try {
        let text =
          '地区：' +
          prarm.orgName +
          '\n公司名称：' +
          prarm.customerName +
          '\n公司税号：' +
          prarm.customerTaxcode +
          '\n来电电话：' +
          prarm.telCalls +
          '\n服务费情况：' +
          prarm.promptMessage +
          '\n到期日期：' +
          prarm.expirationDate +
          '\n需求：' +
          prarm.questionContent
        await toClipboard(text)
        proxy.$message.success('复制成功')
      } catch (e) {
        console.error(e)
        proxy.$message.error('复制失败')
      }
      break
    case 'abnormal':
      //异常单据 问题分类，问题描述，答案 来电电话 必填
      if (
        !formData.value.questionTypeId ||
        !formData.value.questionContent ||
        !formData.value.questionAnswer ||
        !props.telCalls
      ) {
        proxy.$message.error('问题分类、问题描述、问题答案、来电电话不能为空')
        return
      }
      let params = JSON.parse(JSON.stringify(formData.value))
      params.mainContactId = phoneRecordInfos.value.mainContactId
      params.mainContactName = phoneRecordInfos.value.mainContactName
      params.mainContactPhone = phoneRecordInfos.value.mainContactPhone
      params.orgId = phoneRecordInfos.value.orgId
      params.personTel = props.telCalls //来电人
      abnormaSaveBtnLoading.value = true
      if (route.query.type == 'edit') {
        //修改
        params.id = route.query.abId
      }
      abnormalSave(params)
        .then(res => {
          abnormaSaveBtnLoading.value = false
          successdialog.value = true
          jumpType.value = 'abnormal'
          getsuccessdialogSencond()
        })
        .finally(e => {
          abnormaSaveBtnLoading.value = false
        })

      break
    default:
      break
  }
}
/******************hock 事件*******/
import { useTransaction } from '@/hooks/dict/phoneRecord'
import { decryptCode, encryptCode } from '@/api/customer/customer'
import { encode_max_count } from '@/hooks/dict/contract'
import axios from 'axios'
import useTagsViewStore from '@/store/modules/tagsView'
const { getDetailByCustomerFn } = useTransaction()
/***********诺诺资质************/
const qualifications = () => {
  let url =
    'https://yygl.jss.com.cn/yystatic/platform.html#!/qyinformation/addservice/' +
    formData.value.customerTaxcode +
    '/dzfp'
  window.open(url, 'scrollbars=yes,resizable=1,modal=false,alwaysRaised=yes')
}
/**************************************问题分类*/
const questionTypeIdSelect = ref([])
const questionTypeOptions = ref([])
const questionTypeProps = ref({
  // checkStrictly: true
})
const filterMethodFn = (node, keyword) => {
  if (!keyword) {
    return true
  }
  let valArr = node.pathValues.filter(item => item.toString().includes(keyword))
  let labelArr = node.pathLabels.filter(item =>
    item.toLowerCase().includes(keyword.toLowerCase())
  )
  return valArr.length || labelArr.length
}

//问题分类 键值转行
const mapTree = org => {
  // 给需要的键名赋值的方法
  const haveChildren = Array.isArray(org.children) && org.children.length > 0
  return {
    label: org.questionTypeName,
    value: org.questionTypeId,
    // 没有子节点了就置空，不然还有空白的节点展示在选择项中占位
    children: haveChildren ? org.children.map(i => mapTree(i)) : null
  }
}
// 根据选中的最后一级的多个 id 设置选中的值
function getAncestors(data, targetId) {
  console.log(data, targetId, 'targetId===')
  // 定义一个递归函数来查找祖先节点
  function findAncestors(node, ancestors = []) {
    if (node.value == targetId) {
      // 如果找到了目标节点，则返回其祖先数组加上目标节点的 ID
      return [...ancestors, node.value]
    }
    for (const child of node.children || []) {
      const result = findAncestors(child, [...ancestors, node.value])
      if (result.length > 0) {
        // 如果递归调用返回了非空数组，则说明找到了目标节点的祖先链
        return result
      }
    }
    return []
  }

  // 遍历所有根节点
  for (const root of data) {
    const result = findAncestors(root, [])
    if (result.length > 0) {
      // 如果在某个根节点中找到了目标节点，则返回结果
      return result
    }
  }

  // 如果没有找到目标节点，则返回空数组
  return []
}
//请求接口的时候
const getquestionType = async () => {
  let data = await questionTyplist()
  if (data.code == 200) {
    questionTypeOptions.value =
      data.data && data.data.length > 0
        ? data.data.map(org => mapTree(org))
        : []
  }
}
// 问题分类 选中的时候
const questionTypePropsChange = (value, selectedData) => {
  if (value) {
    let selectVal = proxy.$refs['questionType'].getCheckedNodes()
    console.log(selectVal, 'selectVal--')
    formData.value.questionTypeId = selectVal ? selectVal[0].data.value : ''
    formData.value.questionTypeName = selectVal ? selectVal[0].data.label : ''
  }
}
/*****************************************客户名称、税号 ---模块*/
const focusTip = () => {
  if (!formData.value.customerName || !formData.value.customerTaxcode) {
    proxy.$modal.msgWarning('请从上面输入框客户名称')
    return false
  }
}
//请求
const customerNameFetch = async (queryString, cb) => {
  console.log('输入关键字：', queryString)
  let results = []
  if (queryString == '') {
    cb(results)
  } else {
    try {
      let params = {
        customerNameOrNumber: queryString || undefined,
        pageNum: 1,
        pageSize: 10
      }
      let cRes = await listByCustomerFromView(params)
      console.log(cRes, 'cRes--')
      if (cRes.rows && cRes.rows.length > 0) {
        results = cRes.rows.map(item => {
          return {
            value: item.customerName,
            id: item.id,
            code: item.customerTaxcode,
            orgId: item.orgId
          }
        })
        isSearchDataNo.value = false
      } else {
        results = [{ default: '无匹配数据' }]
        isSearchDataNo.value = true
      }

      cb(results)
    } catch (e) {
      proxy.$modal.msgError(e.msg)
    }
  }
}
//选中
const customerNameSelect = item => {
  console.log('选中', toRaw(item))
  sessionStorage.removeItem('isShowTis')
  // questionTypeIdSelect.value = []
  // formData.value.questionContent = ''
  // formData.value.questionAnswer = ''
  // formData.value.questionTypeId = ''
  // formData.value.questionTypeName = ''
  formData.value.customerTaxcode = toRaw(item).code
  formData.value.customerName = toRaw(item).value
  formData.value.customerId = toRaw(item).id
  recordListFn()
  // 主要代码
  // document.activeElement获得了DOM中被聚焦的元素；.blur()取消聚焦
  document.activeElement.blur()
}
/******************************************产品名称 **/
const productOptions = ref([]) // 原值 产品名称数据
const filteredOptions = ref([]) //过滤后的产品名称数据

const productIdfilterMethod = keyword => {
  if (!keyword) {
    // 如果没有输入查询，则返回所有选项
    filteredOptions.value = JSON.parse(JSON.stringify(productOptions.value))
    return
  }
  // 将查询转换为小写，以便进行不区分大小写的搜索
  keyword = keyword.toLowerCase()
  filteredOptions.value = productOptions.value.filter(option => {
    // 检查 label 和 value 是否包含查询字符串
    return (
      option.productName.replace(/\s/g, '').toLowerCase().includes(keyword) ||
      option.productId.toString().includes(keyword)
    )
  })
}
//选中
const productChange = val => {
  let productOption = JSON.parse(JSON.stringify(productOptions.value))
  if (val) {
    let row = find(productOption, { productId: val })
    formData.value.productName = row?.productName
  }
}
/******************************************* 所属税务机关  **/
const taxTreeData = ref([])
const getTaxTreeDatafn = () => {
  // 获取税务机关下拉数据
  commonStore.getTaxTreeData().then(data => {
    taxTreeData.value = data
  })
}
/***************************************************  来电记录   */
const phoneRecordInfos = ref({}) //来电记录信息 所有
const emit = defineEmits(['childParam'])
const tableList = ref([])
const fillFormData = (sourceData, targetForm) => {
  for (const key in sourceData) {
    if (sourceData.hasOwnProperty(key)) {
      const value = sourceData[key]
      if (targetForm.hasOwnProperty(key)) {
        if (
          key == 'questionAnswer' ||
          key == 'questionContent' ||
          key == 'questionTypeName' ||
          key == 'productName'
        ) {
          // 问题答案和描述
          targetForm[key] = value ? value : formData.value[key]
        } else if (key == 'questionTypeId') {
          // 问题分类
          questionTypeIdSelect.value =
            value == null
              ? questionTypeIdSelect.value
              : getAncestors(questionTypeOptions.value, value)
          targetForm[key] = value ? value : formData.value[key]
        } else if (key == 'productId') {
          //产品名称
          targetForm[key] = value ? value.toString() : ''
        } else {
          targetForm[key] = value ? value : ''
        }
      }
    }
  }
}
//获取详情数据
const getData = (Dres, type) => {
  phoneRecordInfos.value = Dres
  let phoneRecordInfosVal = JSON.parse(JSON.stringify(Dres))
  phoneRecordInfosVal.childParamTypes = type //子组件传值
  phoneRecordInfosVal.isCustomerName = customerNameOrNumber.value ? true : false //是否搜索税号查询的数据
  emit('childParam', phoneRecordInfosVal)
  getSelectAddress(Dres.customerId, Dres.selectAddress)
  fillFormData(Dres, formData.value)
  if (phoneRecordInfos.value.customerTaxcode) {
    getLevel({
      customerTaxcode: phoneRecordInfos.value.customerTaxcode,
      orgId: phoneRecordInfos.value.orgId
    }).then(res => {
      formData.value.memberLevel = res.data
    })
  }

  formData.value.isCancel = Dres.isCancel ? Dres.isCancel : '0'
  formData.value.isDigital = Dres.isDigital ? Dres.isDigital : '0'
  formData.value.starRating = Dres.starRating ? Dres.starRating : '0'
  formData.value.isDispatch = Dres.isDispatch ? Dres.isDispatch : '0'
  formData.value.dispatchAddress = Dres.dispatchAddress || Dres.address //派单地址
  formData.value.dispatchContact = Dres.dispatchContact || Dres.mainContactName //派单联系人
  formData.value.dispatchPhone = Dres.dispatchPhone || Dres.mainContactPhone //派单联系电话
  formData.value.telDate = Dres.telDate
  formData.value.userName = Dres.userName
  formData.value.userId = Dres.userId
  if (!formData.value.processMode) {
    formData.value.processMode = '2' //默认 远程服务
  }
  //派工类型 为空的时候
  if (!formData.value.sendTypeId) {
    formData.value.sendTypeId = '1' //维护
  }
  //来电类型 为空的时候
  if (!formData.value.type) {
    callType()
  }
  // 转换星级字段属性
  if (Dres.starRating != null) {
    formData.value.starRating = parseInt(Dres.starRating)
  }
  //转换所属税务机关属性
  if (Dres.taxdeptCode) {
    console.log(taxTreeData.value, '333')
    formData.value.taxdeptCode = parseInt(Dres.taxdeptCode)
  } else {
    formData.value.taxdeptCode = ''
  }
  if (Dres.productId) {
    formData.value.productId = Dres.productId + ''
  }

  //预约时间 默认是第二个工作日
  if (!formData.value.reservationDate) {
    formData.value.reservationDate = getSecondBusinessDayFromToday()
  }
  if (!formData.value.reservationPeriod) {
    formData.value.reservationPeriod = '全天'
  }
  if (!formData.value.startDate) {
    formData.value.startDate = format(new Date(), 'yyyy-MM-dd HH:mm:ss')
  }
  if (route.query.TAX_CODE) {
    formData.value.isNuoYan = 1
  }
  proxy.$nextTick(() => {
    proxy.$refs['ruleForm'].clearValidate()
  })
  recordList({
    customerTaxcode: formData.value.customerTaxcode,
    orgId: Dres?.orgId,
    pageNum: 1,
    pageSize: 8
  }).then(res => {
    tableList.value = res.rows
  })
}
const recordListFn = async type => {
  getDetailByCustomerFn(formData.value.customerId, Dres => {
    getData(Dres, 'phoneRecordInfos')
  })
}

const clearFn = () => {
  formData.value = formDataVal
  formData.value.reservationDate = getSecondBusinessDayFromToday()
  callType()
  proxy.resetForm('ruleForm')
}
/*****来电类型默认**************/
const callType = () => {
  let row = biz_call_record_type.value.find(item1 => item1.remark == '默认')
  formData.value.type = row ? row.value : ''
}
/****************纳税人性质************/
// 改变性质
const taxNatureFn = val => {
  let taxGradeName = tax_grade.value.find(item1 => item1.value == val)
    ? tax_grade.value.find(item2 => item2.value == val).label
    : null
  emit('childParam', {
    childParamTypes: 'taxNature',
    taxNature: val,
    taxNatureName: taxGradeName
  })
}
/**************保存****************************/
const saveBtnLoading = ref(false)
const saveFn = () => {
  proxy.$refs['ruleForm'].validate(valid => {
    if (valid) {
      // if (Number(formData.value.starRating) <= 0) {
      //   proxy.$modal.msgWarning('客户星级为空')
      //   return false
      // }
      if (formData.value.isDigital == 1) {
        if (!formData.value.digitalInfo) {
          proxy.$modal.msgWarning('数电信息为空')
          return false
        }
      }
      if (formData.value.isDispatch == 1) {
        if (!formData.value.reservationDate) {
          proxy.$modal.msgWarning('预约时间不能为空')
          return false
        }
        if (
          formData.value.reservationDate &&
          !formData.value.reservationPeriod
        ) {
          proxy.$modal.msgWarning('预约时间段不能为空')
          return false
        }
      }

      if (!formData.value.questionTypeId) {
        proxy.$modal.msgWarning('问题分类不能为空')
        return false
      }
      let params = JSON.parse(JSON.stringify(formData.value))
      params.mainContactId = phoneRecordInfos.value.mainContactId
      params.mainContactName = phoneRecordInfos.value.mainContactName
      params.mainContactPhone = phoneRecordInfos.value.mainContactPhone
      params.orgId = phoneRecordInfos.value.orgId
      params.personTel = props.telCalls //来电人
      params.productId = '2504'
      params.productName = '其 它'
      if (route.query.TAX_CODE || phoneRecordInfos.value.isNuoYan == '1') {
        //TAX_CODE 存在就是诺言跳转过来
        if (!formData.value.processMode) {
          proxy.$modal.msgWarning('处理方式不能为空')
          return false
        }
        if (!formData.value.startDate) {
          proxy.$modal.msgWarning('开始时间不能为空')
          return false
        }
        if (!formData.value.finishDate) {
          proxy.$modal.msgWarning('结束时间不能为空')
          return false
        }
        params.isNuoYan = '1'
        params.type = '3' //默认远程
      } else {
        delete params.processMode
        delete params.startDate
        delete params.finishDate
        params.isNuoYan = '0'
      }
      saveBtnLoading.value = true
      if (route.query.type == 'edit') {
        //修改
        params.id = route.query.id
        callRecordUpdate(params)
          .then(res => {
            successdialog.value = true
            jumpType.value = 'save'
            getsuccessdialogSencond()
          })
          .finally(e => {
            saveBtnLoading.value = false
          })
      } else {
        callRecordSave(params)
          .then(res => {
            successdialog.value = true
            jumpType.value = 'save'
            getsuccessdialogSencond()
          })
          .finally(e => {
            saveBtnLoading.value = false
          })
      }
    } else {
      console.log('error submit!!')
      return false
    }
  })
}
// 保存成功 后 操作
const successdialog = ref(false)
const successdialogSencond = ref(3) ////设置初始倒计时
// 倒计时
const getsuccessdialogSencond = () => {
  const interval = window.setInterval(function () {
    --successdialogSencond.value
    if (successdialogSencond.value === 0) {
      window.clearInterval(interval)
      successdialogClose() //倒计时结束时运行的业务逻辑，这里的是关闭当前页面
    }
  }, 1000)
}
// 关闭 弹出框
const jumpType = ref('save')
const successdialogClose = () => {
  console.log(window.location.pathname, jumpType.value, '1111')
  if (
    window.location.pathname == '/callCenter/telephoneRecords/phoneRecordSheet'
  ) {
    if (jumpType.value == 'save') {
      //系统内部列表
      router.push({
        path: '/callCenter/telephoneRecords/workOrderList'
      })
    } else {
      //异常单据
      router.push({
        path: '/callCenter/telephoneRecords/abnormalDocuments'
      })
    }

    useTagsViewStore().delView(router.currentRoute.value)
  } else if (window.location.pathname == '/phoneRecordSheet') {
    // 弹出框
    closePage()
  }
  successdialog.value = false
}
/**********************获取最新*******************************/
//  税号加密 =》 调接口 =》取返回值调接口解密 =》显示内容 =》是否更新到erp
// 获取最新 -校验最新
async function checkInfo() {
  try {
    // 1.税号加密
    const encode = await encryptCode({
      nsrsbh: formData.value.customerTaxcode,
      max: Number(ref(encode_max_count).value[0].value)
    })
    // 测试环境：http://222.76.49.184:8021/TamClientT/doService.do
    //正式环境：http://222.76.49.184:8021/TamClient/doService.do
    let tamClientUrl = import.meta.env.VITE_TamClient_URL
    axios
      .post(tamClientUrl, encode.msg, {
        headers: {
          'Content-Type': 'text/plain' // 设置Content-Type为纯文本
        }
      })
      .then(async res => {
        // 2.税号解密
        const decode = await decryptCode({ nsrsbh: res.data })
        console.log(decode, 'decode--')
        if (decode.code === 200) {
        }
      })
      .finally(() => {})
  } catch (error) {
    console.error(error, 'catch')
  }
}
/**********************关闭页面*****************end**************/
//关闭页面
const closePage = () => {
  if (window.opener) {
    // 关闭当前窗口
    window.close()
  } else {
    window.history.back()
  }
}
/**********************获取最新*****************end**************/
// 预约时间默认第二个工作日
function getSecondBusinessDayFromToday() {
  const today = new Date()
  const dayOfWeek = today.getDay()
  let daysToAdd

  if (dayOfWeek === 5) {
    // 如果今天是周五
    daysToAdd = 3 // 跳到下周一
  } else if (dayOfWeek === 6) {
    // 如果今天是周六
    daysToAdd = 2 // 跳到下周一
  } else {
    // 如果今天是周一到周四
    daysToAdd = 1 // 两个工作日
  }

  // 计算第二个工作日的日期
  const resultDate = new Date(today)
  resultDate.setDate(resultDate.getDate() + daysToAdd)
  // 格式化为YYYY-MM-DD
  const formattedDate = resultDate.toISOString().split('T')[0]
  return formattedDate
}

/**********************获取最新*****************end**************/
/*****选择地址************************************start***************/
const selectAddressArr = ref([])
const getSelectAddress = (id, addressId) => {
  getDetailTactlist({ id: id, pageNum: 1, pageSize: 99999 }).then(res => {
    selectAddressArr.value = res.data.records
    if (!addressId) {
      formData.value.addrName =
        res.data.records && res.data.records.length > 0
          ? res.data.records[0].addressName
          : ''
      formData.value.selectAddress =
        res.data.records && res.data.records.length > 0
          ? res.data.records[0].id
          : ''
    } else {
      formData.value.selectAddress = addressId
    }
  })
}
const selectAddressChange = val => {
  let row = selectAddressArr.value.find(item2 => item2.id == val)
  formData.value.dispatchAddress = row.address || '' //派单地址
  formData.value.dispatchContact = row.contactName || '' //派单联系人
  formData.value.dispatchPhone = row.contactNumber || '' //派单联系电话
  formData.value.addrName = row.addressName || ''
}
/*****选择地址************************************end***************/
async function inifn() {
  //预约时间 默认是第二个工作日
  formData.value.reservationDate = getSecondBusinessDayFromToday()
  await getTaxTreeDatafn()

  // // 产品名称
  // productList({
  //   pageNum: 1,
  //   pageSize: 99999
  // })
  //   .then(res => {
  //     productOptions.value = res.rows
  //     filteredOptions.value = res.rows
  //   })
  //   .catch(e => {
  //     productOptions.value = []
  //   })
}
// 如果你仍然想要使用 nextTick，可以这样做
watch(biz_call_record_type, newVal => {
  if (newVal !== undefined) {
    callType()
  }
})
/************异常单据模块**************/
const abnormalDetails = async () => {
  let res = await abnormalDeatils(route.query.abId)
  if (res.code == 200) {
    getData(res.data, 'detail')
  }
}
const isPopUP = ref('system') //异常单据显示 系统访问的时候展示，其他不展示
watch(
  () => props.paramData,
  async val => {
    console.log(val, 'val--')
    await getquestionType()
    if (JSON.stringify(val) != '{}') {
      console.log('企业信息接收参数4444：', val)
      formData.value.customerId = val.customerId || ''
      customerNameOrNumber.value = ''
      isPopUP.value = val.isPopUP
      if (!val.customerId) {
        clearFn()
        return false
      }
      if (val.type == 'details') {
        // 工单列表记录单详情 -从工单id
        initDetail()
        isEdit.value = route.query.type == 'edit' ? true : false
        isDetail.value = route.query.type == 'detail' ? true : false
        return
      }
      if (val.type == 'abnormalDetails') {
        console.log(props.paramData, '2222222 的活得好好的好的好的')
        // 异常单据列表--进入
        abnormalDetails()
        return
      }
      recordListFn('paramData')
    }
  },
  {
    immediate: true,
    deep: true
  }
)
//   //从工单列表跳转过来的
const initDetail = async () => {
  let res = await callRecordDetail(route.query.id)
  if (res.code == 200) {
    getData(res.data, 'detail')
  }
}
const isDetail = ref(false) //只能查看详情
const isEdit = ref(false) //是否可以编辑

inifn()
</script>

<style lang="scss" scoped></style>
